import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'zhuye',
    meta: {
      num: 0
    },
    component: () => import('../views/Home'),
    children: [
      {
        path: 'popup',
        name: 'MyPopup',
        component: () => import('../views/MyPopup'),
      }
    ]
  },
  {
    path: '/topic',
    meta: {
      num: 1
    },
    name: 'Topic',
    component: () => import('../views/topic'),
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      num: 2
    },
    component: () => import('../views/category'),
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      num: 3
    },
    component: () => import('../views/cart'),
  },
  {
    path: '/user',
    name: 'User',
    meta: {
      num: 4
    },
    component: () => import('../views/user'),
  },
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('../views/ProductDetail'),
  },
  {
    path: '/brandDetail',
    name: 'BrandDetail',
    component: () => import('../views/BrandDetail'),
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {

  let token = localStorage.getItem('token');

  if (to.path == '/cart') {
    if (token) {
      next()
    }
    else {
      Vue.prototype.$toast('请先登录');
      setTimeout(() => {
        next('/user');
      }, 100);
    }
  }
  // 让页面回到顶部
  document.documentElement.scrollTop = 0;
  next();
})

export default router
